//
// Created by 11197 on 25-5-12.
//

#include <QVBoxLayout>
#include <QDateTime>

#include "LoginWgt.h"
#include "../tool/StyleLoader.h"

// TODO: 完善登录逻辑

LoginWgt::LoginWgt(QWidget *parent)
{

    socket_ = new QTcpSocket(this);
    connect(socket_, SIGNAL(readyRead()), this, SLOT(ReadData()));
    socket_->connectToHost("192.168.31.38", 8523);
    if(socket_->waitForConnected(1000)){
        isConnected_ = true;
        qDebug() << "注册负载成功";
    }

    setWindowFlag(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_StyledBackground);
    setFixedSize(600,510);

    accountEdit_ = new QLineEdit(this);
    passwordEdit_ = new QLineEdit(this);
    loginBtn_ = new QPushButton(QString("登录"), this);

    // TODO: 这里直接给出了信令服务器的地址
    connect(loginBtn_, &QPushButton::clicked, this, [this]() {
        emit sig_logined("192.168.31.38", 6539);
    });

    this->setObjectName("Loginer");
    accountEdit_->setObjectName("AcountEdit");
    passwordEdit_->setObjectName("PasswdEdit");
    loginBtn_->setObjectName("login_Btn");

    accountEdit_->setPlaceholderText(QString("请输入账号"));
    passwordEdit_->setPlaceholderText(QString("请输入密码"));
    passwordEdit_->setEchoMode(QLineEdit::Password);

    QVBoxLayout *layout = new QVBoxLayout(this);

    layout->addStretch(1);
    layout->addWidget(accountEdit_, 0, Qt::AlignHCenter);
    layout->addSpacing(30);
    layout->addWidget(passwordEdit_, 1, Qt::AlignHCenter);
    layout->addSpacing(30);
    layout->addWidget(loginBtn_, 2, Qt::AlignHCenter);
    layout->addStretch(1);
    setLayout(layout);
    StyleLoader::getInstance()->loadStyle(":/UI/brown/main.css",this);

}

uint64_t GetTimeStamp(){
    QDateTime currentDataTime = QDateTime::currentDateTime();
    qint64 timestamp = currentDataTime.toSecsSinceEpoch();
    return static_cast<uint64_t>(timestamp);
}

void LoginWgt::ReadData()
{
    QByteArray buf = socket_->readAll();
    if(!buf.isEmpty()){
        HandleMessage((packet_head*)buf.data());
    }
}

void LoginWgt::HandleMessage(const packet_head *data)
{
    switch (data->cmd) {
    case LOGIN:
        HandleLogin((LoginResult*)data);
        break;
    case REGISTER:
        HandleRegister((RegisterResult*)data);
        break;
    case ERROR_:
        HandleError((packet_head*)data);
        break;
    default:
        break;
    }
}

void LoginWgt::HandleRegister(RegisterResult *data)
{
    if(data->result == S_OK_){
        qDebug() << "register successful";
    }
    else{
        qDebug() << "register failed";
    }
}

void LoginWgt::HandleLogin(LoginResult *data)
{
    // 登录有两个回应
    if(isLogin_){ // 登录服务器返回信令服务器的IP Port
        if(data->result == S_OK_)
        {
            std::string sigserver = data->GetIP();
            qDebug() << "login successful" << "sigIP" << sigserver.c_str() << "port" << data->port;
            emit sig_logined(data->GetIP(), data->port);
        }
    }
    else // 负载均衡返回的是登录服务器IP Port
    {
        HandleLoadLogin((LoginReply*)data);
    }
}

void LoginWgt::HandleError(const packet_head *data)
{

}

void LoginWgt::HandleLoadLogin(LoginReply *data)
{
    ip_= QString(data->ip.data());
    port_ = data->port;
    qDebug() << "login ip: " << ip_ << "port: " << port_;

    // 获取到登录服务器
    socket_->disconnectFromHost();
    isConnected_ = false;
    socket_->connectToHost(ip_, port_);
    if(socket_->waitForConnected(1000)){
        isConnected_ = true;
        isLogin_ = true;
        qDebug() << "登录服务器";

        // 开始登录
        UserLogin login;

        QString account = accountEdit_->text();
        QString password = passwordEdit_->text();
        login.SetCode("123");
        login.SetCount(account.toStdString());
        login.SetPasswd(password.toStdString());
        login.timestamp = GetTimeStamp();
        socket_->write((const char*)&login, login.len);
        socket_->flush();
    }
}
